package com.itboye.sunsunhome.www.aq.base;

import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.itboye.sunsunhome.www.aq.AddDeviceActivity;
import com.itboye.sunsunhome.www.aq.DeviceActivity;
import com.itboye.sunsunhome.www.aq.DeviceConsoleActivity;
import com.itboye.sunsunhome.www.aq.DeviceOptionActivity;
import com.itboye.sunsunhome.www.aq.EditDeviceActivity;
import com.itboye.sunsunhome.www.aq.ManualAddDeviceActivity;
import com.itboye.sunsunhome.www.aq.PeriodActivity;
import com.itboye.sunsunhome.www.aq.SmartConfigActivity;
import com.p2p.pppp_api.PPPP_APIs;
import com.starxnet.ipn.iPN_API;

/**  
 * 2016 4/16 赵武修改版
 * Created by 赵武 on 2015/3/3.
 * 日期：2015-05-18
 * 		1. 解决自定义设备名称受到密码更变后引起的恢复默认BUG
 * 日期：2015-06-30
 * 		1. 添加Wifi密码暂存功能
 * 日期：2016-04-16
 * 		1. 解决网络无连接情况下初始化P2P和iPN会出现死循环的问题
 */
public class MyApplication extends Application {

	public AqPush mPush;
	public Database mDatabase;
	public Context mContext;
	public ArrayList<AqDeviceInfo> mMyDeviceList = null;
	public ArrayList<AqDeviceInfo> mLanDeviceList = null;
	public AqDeviceFind mDeviceFind;
	public AqSmartConfig mSmartConfig;
	public AqDevice mCurrentDevice;
	public AqDeviceInfo mEditDeviceInfo;

	public ServerInfoRead mServerInfoRead;		// 广告读取接口
	public static Context context;
	public String mWifiSSID;
	public String mWifiPassword;

	// 界面
	public SmartConfigActivity mSmartConfigUi;
	public DeviceActivity mDeviceUi;
	public AddDeviceActivity mAddDeviceUi;
	public PeriodActivity mPeriodUi;
	public DeviceConsoleActivity mDeviceConsoleUi;
	public DeviceOptionActivity mDeviceOptionUi;
	public EditDeviceActivity mEditDeviceUi;
	public ManualAddDeviceActivity mManualAddDeviceUi;

	// 初始化线程用互斥
	public String mStringInitPPPP = "mStringInitPPPP";
	public boolean mInitPPPP = false;

	public int initPPPP() {
		int nRet = PPPP_APIs.PPPP_Initialize(AppConfig.PPPP_initString.getBytes());
		return nRet;
	}

	public int initIPN() {
		int nRet = iPN_API.iPN_Initialize(AppConfig.iPN_initString, AppConfig.iPN_AESKey);
		return nRet;
	}

	public boolean initPPPP_iPN() {
		// 初始化线程
		ExecutorService transThread = Executors.newSingleThreadExecutor();
		Runnable mSender = new Runnable() {
			@Override
			public void run() {
				initPPPP();
				initIPN();
				synchronized (mStringInitPPPP) {
					mInitPPPP = true;
				}
			}
		};
		Future transPending = transThread.submit(mSender);
		// 最长等待2秒
		for (int i=0; i<100; i++) {
			try {
				Thread.sleep(20);
			} catch (InterruptedException e) {
				break;
			}
			synchronized (mStringInitPPPP) {
				if (mInitPPPP) {
					transPending.cancel(true);
					// 初始化P2P成功
					return true;
				}
			}
		}
		// 初始化P2P超时，初始化线程还会继续在后台运行
		transPending.cancel(true);
		return false;
	}

	 
	public void init() {
		if (mInitPPPP) {
			return;
		}
		initPPPP_iPN();
		mWifiSSID = "";
		mWifiPassword = "";
		mContext = getApplicationContext();
		context=mContext;
		mCurrentDevice = null;
		mEditDeviceInfo = null;
		mPush = new AqPush(mContext);
		mDatabase = new Database(mContext);
		mMyDeviceList = mDatabase.getAllDeviceInfo();
		mLanDeviceList = new ArrayList<AqDeviceInfo>();
		mDeviceFind = new AqDeviceFind(mHandler);
		mDeviceFind.start(AppConfig.Find_Device_Port);
		mSmartConfig = new AqSmartConfig(mContext);
		mServerInfoRead = new ServerInfoRead(this);
	}

	/**
	 * 添加设备，并存储设备，自动删除重复
	 *
	 * @param deviceInfo 新设备信息
	 */
	public void addDevice(AqDeviceInfo deviceInfo) {
		if (deviceInfo != null) {
			mDatabase.saveDeviceInfo(deviceInfo);
		}
		boolean isNew = true;
		for (int i = 0; i < mMyDeviceList.size(); i++) {
			AqDeviceInfo d = mMyDeviceList.get(i);
			if (deviceInfo.mDid.equalsIgnoreCase(d.mDid)) {
				d.mPassword = deviceInfo.mPassword;
				d.mDeviceName = deviceInfo.mDeviceName;
				isNew = false;
			}
		}
		if (isNew) {
			mMyDeviceList.add(deviceInfo);
		}
		if (mDeviceUi != null) {
			// 刷新已添加设备列表
			mDeviceUi.refreshDeviceList();
		}
	}

	/**
	 * 删除指定设备
	 *
	 * @param deviceInfo 设备信息
	 */
	public void removeDevice(AqDeviceInfo deviceInfo) {
		if (deviceInfo != null) {
			mDatabase.deleteDeviceInfo(deviceInfo);
		}
		for (int i = 0; i < mMyDeviceList.size(); i++) {
			AqDeviceInfo d = mMyDeviceList.get(i);
			if (deviceInfo.mDid.equalsIgnoreCase(d.mDid)) {
				mMyDeviceList.remove(i);
				if (mDeviceUi != null) {
					// 刷新已添加设备列表
					mDeviceUi.refreshDeviceList();
				}
				break;
			}
		}
	}

	private void findNewDeviceProcess(AqDeviceInfo deviceInfo) {
		// 排除无效信息
		if (deviceInfo == null) {
			return;
		}
		if (deviceInfo.mPassword.equals("")) {
			// 屏蔽空密码局域网设备
			return;
		}
		// 局域网设备列表刷新
		boolean lanIsChange = true;
		boolean lanIsNewDevice = true;
		for (int i = 0; i < mLanDeviceList.size(); i++) {
			AqDeviceInfo d = mLanDeviceList.get(i);
			if (deviceInfo.mDid.equalsIgnoreCase(d.mDid)) {
				// 局域网设备列表中已经存在改设备信息
				if (deviceInfo.mPassword.equals("")) {
					// 屏蔽空密码局域网设备
					mLanDeviceList.remove(i);
					lanIsChange = true;
					break;
				}
				lanIsNewDevice = false;
				if (!deviceInfo.mPassword.equals(d.mPassword)) {
					// 密码发生改变，更新密码
					d.mPassword = deviceInfo.mPassword;
					lanIsChange = true;
				} else {
					lanIsChange = false;
				}
				break;
			}
		}
		if (lanIsNewDevice) {
			// 添加新设备信息到局域网设备信息列表
			mLanDeviceList.add(deviceInfo);
		}
		if (lanIsChange) {
			if (mAddDeviceUi != null) {
				// 通知添加局域网设备列表界面，局域网设备列表已经发生改变
				mAddDeviceUi.refreshDeviceList();
			}
		}
		// 已添加设备列表刷新
		boolean deviceIsChange = false;
		for (int i = 0; i < mMyDeviceList.size(); i++) {
			AqDeviceInfo d = mMyDeviceList.get(i);
			if (deviceInfo.mDid.equalsIgnoreCase(d.mDid)) {
				if (!deviceInfo.mPassword.equals(d.mPassword)) {
					// 密码发生改变，更新密码
					d.mPassword = deviceInfo.mPassword;
					deviceInfo = d;
					// 重新添加设备
					addDevice(d);
					// 重新存储设备
					deviceIsChange = true;
				}
				break;
			}
		}
		if ((lanIsChange == true) || (lanIsNewDevice==true) || (deviceIsChange==true)) {
			if (mSmartConfigUi != null) {
				// 通知简易配置界面已经获得新设备信息
				mSmartConfigUi.findNewDeviceInfo(deviceInfo);
			}
		}
	}

	public Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == MessageWhat.DeviceMessage) {
				AqDeviceMessage msgObj = (AqDeviceMessage) msg.obj;
				switch (msgObj.mMessageType) {
					case FindLanDevice:
						// 查找到一个设备
						findNewDeviceProcess(msgObj.mDeviceInfo);
						return;
					default:
						break;
				}
			}
			// 以下注意顺序
			// 交给设备设置界面
			if (mDeviceOptionUi != null) {
				mDeviceOptionUi.newMessage(msg);
			}
			// 交给设备控制界面
			else if (mDeviceConsoleUi != null) {
				mDeviceConsoleUi.newMessage(msg);
			}
			// 交给设备界面处理
			else if (mDeviceUi != null) {
				mDeviceUi.newMessage(msg);
			}

		}
	};
}
